package com.applicationLayer.utility;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;


public class EmailSender {
	
	Logger logger = Logger.getLogger(EmailSender.class);
	
	final private String host="smtp.gmail.com";
	final private String userName="carsharingapplication@gmail.com";
	final private String password="BafalouEstMagique";
		  private String port;
		  private InternetAddress from;
		  private Session session;
		  
	/*Constructor:
	 * 	from:
	 */
		  
	public EmailSender(boolean SSL) throws AddressException{
		
		//Initianilisation connexion
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		if(SSL==true){
			this.setPort("467");//Port for SSL: 465	
		}else{
			this.setPort("587");//Port for TLS/STARTTLS: 587
		}
		props.put("mail.smtp.port", port);
		
				
		//creation connexion
		 this.session = Session.getInstance(props,
				  									new javax.mail.Authenticator() {
																protected PasswordAuthentication getPasswordAuthentication() {
																			return new PasswordAuthentication(userName, password);
																}
		 											}
				 						);
		 logger.warn("SSL MODE:"+SSL);
		 logger.warn("GOOGLE ACCOUNT use:"+userName);
		 logger.info("Email Session create");
	}
	
	
	
	
	
	/**
	 * sendEmail
	 * @param SSLsend
	 * @return
	 */
	public boolean sendClassicEmail(List<String>recipientList,String object,String content){
		logger.info("sendClassicEmail...");
			
		//creation message
		try {
			 
			Message message = new MimeMessage(session);
			//From du mail
			message.setFrom(this.getFrom());
			
			//Liste de diffusion
			Address[] EmailArray=this.transformList_TO_AdressArray(recipientList);
			message.setRecipients(Message.RecipientType.TO,EmailArray);
			
			//Mail Object
			message.setSubject(object);
			
			//Contenu
			message.setText(content);
			logger.warn(content);
			System.out.println("Before sending everything ok");
			//Send
			Transport.send(message);
		}catch (Exception e) {
			System.out.println("Error");
			return false;
		}
		
		

		return true;
	}
	
	
	
	/**$
	 * Send HTML EMail
	 * @param recipientList
	 * @param object
	 * @param content
	 * @return
	 * @throws MessagingException 
	 */
	public boolean sendHTMLEmail(List<String>recipientList,String object,String content,String imagePath) throws MessagingException{
		
		
		String file =imagePath;

		// Create the message
		Message message = new MimeMessage(session);

		// Fill its headers
		message.setSubject(object);
		message.setFrom(from);
		
		//Liste de diffusion
		Address[] EmailArray=this.transformList_TO_AdressArray(recipientList);
		message.setRecipients(Message.RecipientType.TO,EmailArray);

		// Create your new message part
		BodyPart messageBodyPart = new MimeBodyPart();
		String htmlText = content + 
		  "+<img src=\"cid:memememe\">";
		messageBodyPart.setContent(htmlText, "text/html");

		// Create a related multi-part to combine the parts
		MimeMultipart multipart = new MimeMultipart("related");
		multipart.addBodyPart(messageBodyPart);

		// Create part for the image
		messageBodyPart = new MimeBodyPart();

		// Fetch the image and associate to part
		
		System.out.println("searching file...");
		DataSource fds = new FileDataSource(file);
		System.out.println("file founnd...");
		messageBodyPart.setDataHandler(new DataHandler(fds));

		messageBodyPart.setHeader("Content-ID","<memememe>");

		// Add part to multi-part
		multipart.addBodyPart(messageBodyPart);

		// Associate multi-part with message
		message.setContent(multipart);
		
		
		//SENDING
		Transport.send(message);
		return true;
	}
	
	
	/**
	 * Transforme une List d'adresse mail en un tableau d'Address
	 * @param recipientList
	 * @return
	 * @throws AddressException
	 */
	private Address[] transformList_TO_AdressArray(List<String>recipientList) throws AddressException{

		//Ajout du ou des destinataires, transformation de la list en String[]
		Address EmailArray[]=new InternetAddress[recipientList.size()];
		for(int i=0;i<recipientList.size();i++){
			 EmailArray[i]=new InternetAddress(recipientList.get(i));
		}	
		return EmailArray;
	}
	
	
	
	/***************************************************************************
	 *                         GETTER AND SETTER                               *
	 **************************************************************************/

	/**
	 * @return the port
	 */
	public String getPort() {
		return port;
	}

	/**
	 * @param port the port to set
	 */
	public void setPort(String port) {
		this.port = port;
	}


	/**
	 * @return the from
	 */
	public InternetAddress getFrom() {
		return from;
	}


	/**
	 * @param from the from to set
	 */
	public void setFrom(InternetAddress from) {
		this.from = from;
	}
	
	
}
